package com.itlong.cloud.controller.current;

/*import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;*/
import com.itlong.cloud.POJO.DTO.app.AppH5OrderDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyMealManageGetVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.LanguageTypeEnum;
import com.itlong.cloud.enumerate.PaySourceEnum;
import com.itlong.cloud.enumerate.ThirdPartPayTypeEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.ErrorCode;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode_en.AppErrorCodeEnumEN;
import com.itlong.cloud.enumerate.ecode_en.BaseErrorCodeEnumEN;
import com.itlong.cloud.paymenthub.IPropertyMealManageServiceClient;
import com.itlong.cloud.paymenthub.IPropertyPaymentServiceClient;
import com.itlong.cloud.paymenthub.IWeChatPayServiceClient;
import com.itlong.cloud.project.app.IAppRoomServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 * APP支付聚合Controller。
 * </desc>
 *
 * @createDate 2018/04/23
 */
@RestController
@RequestMapping("/pay")
@RefreshScope
public class AppPayController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(AppPayController.class);

    @Autowired
    IWeChatPayServiceClient wechatPayServiceClient;

    @Autowired
    private IPropertyPaymentServiceClient iPropertyPaymentServiceClient;

    @Autowired
    IAppRoomServiceClient iAppRoomServiceClient;

    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    @Value("${" + PlatformConstants.APP_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String APP_REQUEST_PARAMS_ENCRYPT_KEY;

    //乘梯缴费
    public static final String PAY_FOR_ELEVATOR = "7";

    /**
     * <desc>
     *      APP支付-调微信后台统一下单接口/商户后台保存订单
     * <desc/>
     *
     * @param total 支付金额
     * @param billsId 账单编号
     * @param feeType 缴费类型 1物业费 2维修费 3临时车缴费 4月卡缴费 7共享电梯
     * @param roomId 房间编号
     * @return 标准化响应结果
     * @author Juguang.S
     * @createDate 2018/4/23
     */
    @LoggerInfo(operateDesc = LogDescConstant.WECHAT_PAYMENT_ORDER)
    @PostMapping(path = "/order")
    @ResponseBody
    @AuthAccessRequired
    public Object saveOrder(String total,String billsId, String token, String createTime,String sign,String language,String feeType,String roomId) {
        //LOG.info("======saveOrder参数：total：" + total);
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
                feeType = request.getAttribute("feeType") == null ? null : request.getAttribute("feeType").toString();
                total = request.getAttribute("total") == null ? null : request.getAttribute("total").toString();
                billsId = request.getAttribute("billsId") == null ? null : request.getAttribute("billsId").toString();
                roomId = request.getAttribute("roomId") == null ? null : request.getAttribute("roomId").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("total",total);
            if(StringUtils.isNotEmpty(feeType)){
                params.put("feeType",feeType);
            }else{
                feeType = "";
            }
            params.put("billsId",billsId);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params, sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }else if (StringUtils.isBlank(total)||StringUtils.isBlank(createTime) || StringUtils.isBlank(billsId)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                    return new MessageVO(errorCode);
                }else if (Double.parseDouble(total) <= 0){
                    return new MessageVO(AppErrorCodeEnum.TRADE_AMCOUNT_ERR.getErrorCode());
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params, sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }else if (StringUtils.isBlank(total)||StringUtils.isBlank(createTime) || StringUtils.isBlank(billsId)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                    return new MessageVO(errorCode);
                }else if (Double.parseDouble(total) <= 0){
                    return new MessageVO(AppErrorCodeEnum.TRADE_AMCOUNT_ERR.getErrorCode());
                }
            }
            //校验第三方支付管理微信支付是否被禁用
            if(wechatPayServiceClient.getThirdPayStatus(ThirdPartPayTypeEnum.WECHAT_PAY.getType())==0){
                return new MessageVO(AppErrorCodeEnum.NOT_ALLOWED_WEICHAT_TRADE.getErrorCode());
            }
            //查询该账单是否已经被完成
            if(wechatPayServiceClient.getBillStatus(billsId)>0){
                return new MessageVO(AppErrorCodeEnum.BILL_PAY_SUCCESS.getErrorCode());
            }
            //查询账单的金额，校验入参金额
            String totalDB = wechatPayServiceClient.getBillTotal(billsId,1);
            if(StringUtils.isNotEmpty(totalDB) && !"5".equals(feeType)){
                BigDecimal totalCheck = new BigDecimal(total);
                BigDecimal totalDBCheck = new BigDecimal(totalDB);
                if(totalCheck.compareTo(totalDBCheck)!=0){
                    return new MessageVO(AppErrorCodeEnum.BILL_PAY_TOTAL_IS_NOT_SAME.getErrorCode());
                }
            }

            String userId = UserTokenUtil.newAPPTokenDecrypt(token,APP_USER_TOKEN_KEY);
            Map<Object,Object> resultMap = wechatPayServiceClient.saveOrder(total,userId,billsId,feeType,"", PaySourceEnum.APP_SOURCE.getType(),null,roomId,request.getRemoteAddr(),null,null);
            if(resultMap.size()==9){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode(): BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
                return new MessageVO(errorCode,resultMap);
            }else{
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),resultMap);
            }

        } catch (Exception e) {
            throw new DataAccessException("【App_微信支付】API返回的数据异常", e);
        }

    }

    /**
     * <desc>
     *      H5支付统一下单
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/24
     */
    @ResponseBody
    @PostMapping(path = "/h5Order")
    @LoggerInfo(operateDesc = LogDescConstant.WECHAT_PAYMENT_ORDER)
    @UnAuthAccessRequired
    public Object saveOrderH5(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            AppH5OrderDTO appH5OrderDTO = HttpProtocolUtil.parseRequestParamToDTO(AppH5OrderDTO.class, request);
            // 验签
            if (!Md5EncryptUtil.checkAppSignValue(appH5OrderDTO, appH5OrderDTO.getSign(), APP_REQUEST_PARAMS_ENCRYPT_KEY)) {
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(appH5OrderDTO.getLanguage()) ?
                        AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode() : AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                return new MessageVO(errorCode);
                //与树新交流后了解到times字段只有当feeType为7（乘梯缴费）时才不可传空
            } else if (StringUtils.isBlank(appH5OrderDTO.getTotal()) || StringUtils.isBlank(appH5OrderDTO.getCreateTime()) || StringUtils.isBlank(appH5OrderDTO.getBillsId())|| (PAY_FOR_ELEVATOR.equals(appH5OrderDTO.getFeeType()) && StringUtils.isBlank(appH5OrderDTO.getTimes()))) {
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(appH5OrderDTO.getLanguage()) ?
                        BaseErrorCodeEnum.NOT_PARAM.getErrorCode() : BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            } else if (Double.parseDouble(appH5OrderDTO.getTotal()) <= 0) {
                return new MessageVO(AppErrorCodeEnum.TRADE_AMCOUNT_ERR.getErrorCode());
            }
            if (StringUtils.isNotBlank(appH5OrderDTO.getBillsId()) && "7".equals(appH5OrderDTO.getFeeType())) {
                Integer status = iPropertyPaymentServiceClient.checkMealStatus(appH5OrderDTO.getBillsId());
                if (status == null || status != 1) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_MEAL_TYPE_IS_UNABLE_ERR.getErrorCode());
                }
            }
            if (StringUtils.isNotBlank(appH5OrderDTO.getBillsId()) && "7".equals(appH5OrderDTO.getFeeType())) {
                if (iPropertyPaymentServiceClient.checkMealInfo(appH5OrderDTO.getBillsId(),appH5OrderDTO.getRoomId()) > 0) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_MEAL_TYPE_IS_USE_ERR.getErrorCode());
                }
            }
            if (StringUtils.isNotBlank(appH5OrderDTO.getBillsId()) && "7".equals(appH5OrderDTO.getFeeType())) {
                Map<String, Object> data = iAppRoomServiceClient.getHomeList(appH5OrderDTO.getProjectId(), appH5OrderDTO.getLoginUserId());
                List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("roomList");
                int flag = 0;//用户是否在当前房间中标记
                for (Map<String, Object> map : list) {
                    if (map.get("roomId") != null && map.get("roomId").toString().equals(appH5OrderDTO.getRoomId())) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0) {
                    return new MessageVO(PropertyErrorCodeEnum.ELEVATOR_USER_IS_NOT_IN_ROOM_ERR.getErrorCode());
                }
            }

            //校验第三方支付管理微信支付是否被禁用
            if (wechatPayServiceClient.getThirdPayStatus(ThirdPartPayTypeEnum.WECHAT_PAY.getType()) == 0) {
                return new MessageVO(AppErrorCodeEnum.NOT_ALLOWED_WEICHAT_TRADE.getErrorCode());
            }
            //查询该账单是否已经被完成
            if (wechatPayServiceClient.getBillStatus(appH5OrderDTO.getBillsId()) > 0) {
                return new MessageVO(AppErrorCodeEnum.BILL_PAY_SUCCESS.getErrorCode());
            }
            //查询账单的金额，校验入参金额
            String totalDB = wechatPayServiceClient.getBillTotal(appH5OrderDTO.getBillsId(), 1);
            if (StringUtils.isNotEmpty(totalDB)) {
                BigDecimal totalCheck = new BigDecimal(appH5OrderDTO.getTotal());
                BigDecimal totalDBCheck = new BigDecimal(totalDB);
                if (totalCheck.compareTo(totalDBCheck) != 0) {
                    return new MessageVO(AppErrorCodeEnum.BILL_PAY_TOTAL_IS_NOT_SAME.getErrorCode());
                }
            }
            String ip = request.getRemoteAddr();
            Map<Object, Object> resultMap;

            //当feeType为7时 mealid=billsId 查询出套餐金额和次数 插入payment_trade表中的金额和次数
            if (StringUtils.isNotBlank(appH5OrderDTO.getBillsId()) && "7".equals(appH5OrderDTO.getFeeType())) {

                resultMap = wechatPayServiceClient.saveOrder(appH5OrderDTO.getTotal(), appH5OrderDTO.getLoginUserId(),
                        appH5OrderDTO.getBillsId(), appH5OrderDTO.getFeeType(), appH5OrderDTO.getOpenId(), PaySourceEnum.H5_SOURCE.getType(), appH5OrderDTO.getDeviceUnique(),appH5OrderDTO.getRoomId(),ip,appH5OrderDTO.getTimes(),appH5OrderDTO.getTotal());
            }else {
               resultMap = wechatPayServiceClient.saveOrder(appH5OrderDTO.getTotal(), appH5OrderDTO.getLoginUserId(),
                        appH5OrderDTO.getBillsId(), appH5OrderDTO.getFeeType(), appH5OrderDTO.getOpenId(), PaySourceEnum.H5_SOURCE.getType(), appH5OrderDTO.getDeviceUnique(),appH5OrderDTO.getRoomId(),ip,null,null);
            }
          //            if (resultMap.size() == 9) {
            ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(appH5OrderDTO.getLanguage()) ?
                    BaseErrorCodeEnum.SUCCESS.getErrorCode() : BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
            return new MessageVO(errorCode, resultMap);
//            } else {
//                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), resultMap);
//            }
        } catch (Exception e) {
            throw new DataAccessException("【App_微信支付】H5支付统一下单失败", e);
        }
    }

    /**
     * <desc>
     * 根据商户订单号查询订单
     * <desc/>
     *
     * @param
     * @return 标准化响应结果
     * @author Juguang.S
     * @createDate 2018/4/25
     */
    @ResponseBody
    @RequestMapping("/getOrderBytradeId")
    public Object getOrderBytradeId(String tradeId, String createTime,String sign,String language) {
        try {
            boolean flag1 = StringUtils.isNotBlank(createTime);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                tradeId = request.getAttribute("tradeId") == null ? null : request.getAttribute("tradeId").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("tradeId",tradeId);
            params.put("createTime",createTime);
            params.put("language",language);
            if (flag1) {
                if (!Md5EncryptUtil.checkAppSign(params, sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }else if (StringUtils.isBlank(tradeId)||StringUtils.isBlank(createTime)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                    return new MessageVO(errorCode);
                }
            } else {
                if (!Md5EncryptUtil.checkAppSignValue(params, sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                    return new MessageVO(errorCode);
                }else if (StringUtils.isBlank(tradeId)||StringUtils.isBlank(createTime)){
                    ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                    return new MessageVO(errorCode);
                }
            }

            Map<String,Object> returnData = wechatPayServiceClient.getOrderBytradeId(tradeId);

            if(returnData.size()==0 || returnData == null){
                return new MessageVO(AppErrorCodeEnum.NOTN_EXISTENT_ORDER.getErrorCode());
            }
            ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.SUCCESS.getErrorCode(): BaseErrorCodeEnumEN.SUCCESS.getErrorCode();
            return new MessageVO(errorCode,returnData);

        } catch (Exception e) {
            throw new DataAccessException("【演示版App_微信支付】API返回的数据异常", e);
        }
    }


    /**
     * <desc>
     * 调支付宝SDK生成订单信息返回APP接口
     * <desc/>
     *
     * @param total 支付金额
     * @return 标准化响应结果
     * @author Juguang.S
     * @createDate 2018/08/16
     */
    /*@PostMapping(path = "/alipay/order")
    @ResponseBody
    @AuthAccessRequired
    public Object alipayOrder(String total, String token, String createTime,String sign,String language) {
        LOG.info("======saveOrder参数：total：" + total);
        try {
            //验签
            *//*Map<String,String> params = new HashMap<>();
            params.put("total",total);
            params.put("createTime",createTime);
            params.put("language",language);
            if (!Md5EncryptUtil.checkAppSign(params, sign,APP_REQUEST_PARAMS_ENCRYPT_KEY)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode(): AppErrorCodeEnumEN.APP_SIGN_ERR.getErrorCode();
                return new MessageVO(errorCode);
            }else if (StringUtils.isBlank(total)||StringUtils.isBlank(createTime)){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.NOT_PARAM.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }else if (Double.parseDouble(total) <= 0){
                ErrorCode errorCode = LanguageTypeEnum.CHINESE.getLanguage().equals(language)?BaseErrorCodeEnum.PARAM_ERR.getErrorCode(): BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
                return new MessageVO(errorCode);
            }*//*

            String url = "https://openapi.alipay.com/gateway.do";
            String appId = "2018081361020299";
            String appPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCANlMptxoZqCPiXOz8pyxG+bdO6+yeZtsa8J0gy236i5g5kw/LbZXzQIl+bn4Lat+G6W5BmJe3oINKyRugcyKHWsL5r36klwJ36Rx+ZoM+LDV4UU5gKrOWvIhqDcC5YnD+xnQZHa0X3TyM9Jk20NgfWUDi/rcgGu/MVepivk2Ew9jG2qsZeOTEVBEY2kAJwpyqOWr7hakwYfnagruXQnBdg3dMkQNCjZrxxBpP/6tQwYSI1wSn/jHO0RpLDLIin99VnUp0EwJ5gwRgQ6E/Iwn8ARFx0km5uBUUuzRFpkEU3ULYSsq6uuezx7IrG0+GN9K9Ay4k0ja9InbaoovNv6ytAgMBAAECggEAFZMOo3JgPfkBMNIaPtmSpc7XfbxNcMo2DG54wk/5DbP3xZhti/nAxdISUOge5aTyQC1/lCItRYUJEsiMkY9OPCCVtpZFZUTT8YGUfeCaLRgbV0e3PI9y8OaAvffaeleKVBTo7GEGA4IC8mUmcwbplzzZoljiT9C4kVXTvxHu0WwzxIcilFD7Iz2mbLF1b/rm06RX2UfByKFJwPeZRnlt08kqZZIgEWZ5L+yec9gltCloXZVxGXzbQ3hvDP6/dCy5iHjeVHQiYALNMlJMB8XxIo8g70IRcN/rsceS1AljcIoAlPA8G88BoTghxjRt8RoffDsEvS3pYbm/RfM1t6oZsQKBgQDxr0R2XoqBXXb+Jnz+oLqSkN0rES4w59NZhYeRLtRqPSqXBzHtsN3KKG5A7j4YauC1VLxzfwmikJT4P3kdkA3NHqKQ860cb6S1bbbIZZ0YdIXKjd4CqTxOe1qtm97jwO2DS1Mg23lvJlVLCsTcqtmjPHjGna9mUyCgdGDP2ZwmCwKBgQCHznFdCrQWmx9VYE6I972wzonyKJA5yIhBwPCHNuAimsC6yX3H9CV+vYA6fzk6NvX3zev8D3e+3rHQZJUOPK0NW8lyWCKDbHPeeXrHWFEWkQoZVhh5gkqke2brO9V9mLVRFA1GPPdutGensudkJnxZgrYGBqgYA2xRiBdOsKNDJwKBgAcCq3y3f1MDUAlNOoD0TpUjyJaQOAPJJbNKEUWf0x+FyK960PLxF23ewFv3zStOJlh8Lb835yKlCP0ucifuXsgdZF/KAbJ6do+gsBWeBPGJp7vZY6A2In6wS1AP3mZC2WDelXm1hA86UG0N0eoItqlqfqJcPpM8RA0Dcy90Q3hDAoGABkZPjpD0CSdZp0Qv3Lw1k3m3fezJ3SGayg70DgtHB9JGnVq56QcqxFRVHF7Mchgf/TcSdC7yxWrcpFhBWssK49cd056m2ZOlNt4+Af/en0BMSydjMhoHANqCwtOc5ZSsq/ZVNq2ScRb8ww7NCh+NF0Wmy1h7Y8CkvI+hJA2dPXkCgYEAxKkXiqTaV8GePmc3P4J4cERWsGHBB+IZssJbMxCwW+8R17SO+xx2DLIYfUbGLvjx5e68r8JfM9yV1jUiqDlXZyDuK0fo7lW/wlNarex1bd1+ZGWVg9Z4Mca6GUhzmsM9+/tzsYtWlB0JXr2zOJbptu7+/+O0sTfR2ifpine3R4Y=";
            String format = "json";
            String charset = "UTF-8";
            String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAszB/0JGvO2A2/q7YM2p9o3T0z8A7Qh/0K405svOzTU73jJIrtvLIm0moWB6RSzz3YG+3buQFBC94erOZI2FbcxtKal/3rHLbpgVOpKsCTtV/B+VdKSFkoR2N2/GdkkT1Q4FfqtWL1kaTDMjrkwBnvY+FSUw6HZkEnVTAxFr0pPR4kMSzTQhGhsbgRQJ9FA7AjqMUd+R58IUjK/kUzLppN22ZlhWSxy8bl+M46T6/UESjDXhfujB3JrzJeUFDGHnVC89dDzhgqvg1+ttXcPz7kQccnKKKa+X8Yqjtp84iUj3tAyzuznNwvi2MLo6qwGEZwYQnnWpD6eSpj35KXntYWQIDAQAB";
            String signType = "RSA2";
            //实例化客户端
            AlipayClient alipayClient = new DefaultAlipayClient(url,appId,appPrivateKey,format,charset,alipayPublicKey,signType);
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody("支付宝APP支付测试");
            model.setSubject("App支付测试Java");
            model.setOutTradeNo(LogicIdUtil.bussinessId());
            model.setTimeoutExpress("30m");
            model.setTotalAmount(total);
            model.setProductCode("QUICK_MSECURITY_PAY");
            request.setBizModel(model);
            request.setNotifyUrl("http://song.tunnel.echomod.cn/app/pay/payResultNotice");
            try {
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
                System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
                String valueStr = response.getBody();
                Map<String,String> resultMap = new HashMap<>();
                resultMap.put("orderInfo",valueStr);
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),resultMap);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            return null;

        } catch (Exception e) {
            throw new DataAccessException("【演示版App_支付宝后台下单】API返回的数据异常", e);
        }
    }*/

    /**
     * <desc>
     * 支付宝支付结果回调通知
     * <desc/>
     *
     * @param
     * @return 商户后台逻辑处理后向微信后台响应SUCCESS的状态的String
     * @author Juguang.S
     * @createDate 2018/8/16
     */
    /*@ResponseBody
    @RequestMapping("/payResultNotice")
    public void payResultNotice(HttpServletRequest request) {
        try {
            System.out.print("微信支付回调获取数据开始");
            LOG.info("微信支付回调获取数据开始");

            String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAszB/0JGvO2A2/q7YM2p9o3T0z8A7Qh/0K405svOzTU73jJIrtvLIm0moWB6RSzz3YG+3buQFBC94erOZI2FbcxtKal/3rHLbpgVOpKsCTtV/B+VdKSFkoR2N2/GdkkT1Q4FfqtWL1kaTDMjrkwBnvY+FSUw6HZkEnVTAxFr0pPR4kMSzTQhGhsbgRQJ9FA7AjqMUd+R58IUjK/kUzLppN22ZlhWSxy8bl+M46T6/UESjDXhfujB3JrzJeUFDGHnVC89dDzhgqvg1+ttXcPz7kQccnKKKa+X8Yqjtp84iUj3tAyzuznNwvi2MLo6qwGEZwYQnnWpD6eSpj35KXntYWQIDAQAB";
            String charset = "UTF-8";
            String signType = "RSA2";

            Map<String,String> params = new HashMap<String,String>();
            Map requestParams = request.getParameterMap();
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            System.out.println("回调返回结果："+params.toString());
            boolean flag = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset,"RSA2");
            System.err.println(flag);
        } catch (Exception e) {
            throw new DataAccessException("【演示版App_支付宝支付】API返回的数据异常", e);
        }
    }*/

}
